package com.easy.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


/**
 * Created with IntelliJ IDEA.
 * User: guyu
 * Date: 14-5-15
 * Time: 下午2:45
 * To change this template use File | Settings | File Templates.
 */
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
        check();

        return (T) applicationContext.getBean(name);
    }

    @SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> clazz) {
        check();

        return (T) applicationContext.getBeansOfType(clazz);
    }

    public static void check() {
        if (applicationContext == null) {
            throw new IllegalStateException("SpringUtil not define in applicationContext.xml");
        }
    }
    
    
}


